'use strict';

/**
 * 注意，使用stream模式处理文件上传时，首先你要修改config.js中的multipart的模式；
 */

const fs = require('mz/fs');
const path = require('path');
const Controller = require('egg').Controller;
const toArray = require('stream-to-array');
const sendToWormhole = require('stream-wormhole');

class UploadBufferController extends Controller {

  async upload() {
    const { ctx } = this;
    const stream = await ctx.getFileStream();
    console.log('stream', stream);
    let buf;
    try {
      const parts = await toArray(stream);
      buf = Buffer.concat(parts);
    } catch (err) {
      await sendToWormhole(stream);
      throw err;
    } finally {
      await sendToWormhole(stream);
    }

    const savePath = path.join(__dirname, '../public/upload/');
    const savePathAbsolute = savePath + `${stream.filename}`;
    await fs.writeFile(savePathAbsolute, buf);

    ctx.helper.renderSuccess(ctx, { data: savePathAbsolute });
  }
}

module.exports = UploadBufferController;
